package com.bee.beemanage.system.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bee.beemanage.api.entity.SysUserLogin;
import com.bee.beemanage.api.mapper.SysUserLoginMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 陈国松
 * 监听redis登录用户令牌过期，删除mysql中对应的登录用户信息
 */
@Component
public class LoginUserListener extends KeyExpirationEventMessageListener {
    @Resource
    private SysUserLoginMapper sysUserLoginMapper;
    private final Logger logger = LoggerFactory.getLogger(LoginUserListener.class);
    public LoginUserListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        super.onMessage(message, pattern);
        String expiredKey = message.toString();
        if(expiredKey.contains("LoginUsers:")){
            String[] split = expiredKey.split(":");
            String Token = split[1];
            QueryWrapper<SysUserLogin> wrapper = new QueryWrapper<>();
            wrapper.eq("token",Token);
            SysUserLogin loginUser = sysUserLoginMapper.selectOne(wrapper);
            if(null!=loginUser){
                sysUserLoginMapper.delete(wrapper);
            }
        }
    }
}
